<form class="area" method="post" style="padding-bottom:40px;">
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">头像</label></dt>
        <dd class="opCon">
            <div id="uploader-demo">
                <!--用来存放item-->
                <input type="hidden" id="img"  value="" />
                <div id="fileList" class="uploader-list"></div>
                <div id="filePicker"  >选择图片</div>
            </div>
        </dd>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">用户名</label></dt>
        <dd class="opCon">
            <input type="text" id="username" class="txt" placeholder="请输入用户名" value="">
            <p class="tip"></p>
        </dd>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">密码</label></dt>
        <dd class="opCon">
            <textarea class="txt"  id="password"  placeholder="请输入密码"></textarea>
            <p class="tip"></p>
        </dd>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">用户角色</label></dt>
        <select name="role" id="role" data="">
            <option value="">
                请选择用户角色
            </option>
            {% for role in allRole %}
            {% if role['name'] !== '超级管理员' %}
            <option value="{{ role['id'] }}">
                {{ role['name'] }}
            </option>
            {% endif %}
            {% endfor %}
        </select>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">真实姓名</label></dt>
        <dd class="opCon">
            <textarea class="txt" id="realName"  placeholder="请输入真实姓名"></textarea>
            <p class="tip"></p>
        </dd>
    </dl>


    <p class="mt20 tc"><input type="button" style="width: 100px; height:30px;" value="提交"   id="btnsubmit"  /> <input type="button" style="width: 100px; height:30px;"  value="返回"  class="btn-back"  /></p>
</form>

<input type="hidden" value="{{url("usermanage/addUser")}}" id="clicksaveRole">

<input type="hidden" id="ajaxAdd" value="{{url("admanage/ajaxAdd")}}">

<link rel="stylesheet" type="text/css" href="{{constant('ADMIN_JS_PATH')}}webuploader-0.1.5/webuploader.css">

<script type="text/javascript" src="{{constant('ADMIN_JS_PATH')}}webuploader-0.1.5/webuploader.nolog.js"></script>



<script type="text/javascript">


var dir = "";
var service = "";
var fileName = "";
// 初始化Web Uploader
var uploader = WebUploader.create({
    // 选完文件后，是否自动上传。
    auto: true,
    // swf文件路径
    swf: "{{constant('ADMIN_JS_PATH')}}webuploader-0.1.5/Uploader.swf",
    // 文件接收服务端。
//    server: 'http://testimg-xuzhong.oss-cn-shanghai.aliyuncs.com',
    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: '#filePicker',
    // 只允许选择图片文件。
    accept: {
        title: 'Images',
        extensions: 'gif,jpg,jpeg,bmp,png',
        mimeTypes: 'image/jpg,image/jpeg,image/png'
    }

});


// 当有文件添加进来的时候
uploader.on('fileQueued', function (file) {
    $.ajax({
        url: "{{constant('APP_URL')}}" + '/Web/getOssSign/type/1',
        type: 'get',
        async: false, //使用同步的方式,true为异步方式
        success: function (res) {
            console.log(res);
            res = res.data;
            dir = res.dir;
            service = res.host;
            uploader.option('formData', {
                "success_action_status": 200,
                "OSSAccessKeyId": res.accessid,
                "policy": res.policy,
                "signature": res.signature
            });
            uploader.option("server", res.host)
//            console.log(uploader)
            //code here...
        },
        dataType: 'json'
    });
    fileName = calculate_object_name(file.name);
    uploader.option('formData', {
        "key": dir + fileName,
    });
    var $li = $(
            '<div id="' + file.id + '" class="file-item thumbnail">' +
            '<img>' +
            '<div class="info">' + service + "/" + dir + fileName + '</div>' +
            '</div>'
            ),
            $img = $li.find('img');
    // $list为容器jQuery实例
    $("#fileList").html($li);
    $("#img").val(service + "/" + dir + fileName);
    // 创建缩略图
    // 如果为非图片文件，可以不用调用此方法。
    // thumbnailWidth x thumbnailHeight 为 100 x 100
    var thumbnailWidth = 200;
    var thumbnailHeight = 200;
    uploader.makeThumb(file, function (error, src) {
        if (error) {
            $img.replaceWith('<span>不能预览</span>');
            return;
        }

        $img.attr('src', src);
    }, thumbnailWidth, thumbnailHeight);
});
// 文件上传过程中创建进度条实时显示。
uploader.on('uploadProgress', function (file, percentage) {
    var $li = $('#' + file.id),
            $percent = $li.find('.progress span');
    // 避免重复创建
    if (!$percent.length) {
        $percent = $('<p class="progress"><span></span></p>')
                .appendTo($li)
                .find('span');
    }

    $percent.css('width', percentage * 100 + '%');
});
// 文件上传成功，给item添加成功class, 用样式标记上传成功。
uploader.on('uploadSuccess', function (file) {
    $('#' + file.id).addClass('upload-state-done');
});
// 文件上传失败，显示上传出错。
uploader.on('uploadError', function (file) {
    var $li = $('#' + file.id),
            $error = $li.find('div.error');
    // 避免重复创建
    if (!$error.length) {
        $error = $('<div class="error"></div>').appendTo($li);
    }

    $error.text('上传失败');
});
// 完成上传完了，成功或者失败，先删除进度条。
uploader.on('uploadComplete', function (file) {
    $('#' + file.id).find('.progress').remove();
});

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    var timestamp = Date.parse(new Date()) / 1000;

    suffix = get_suffix(filename)
    g_object_name = random_string(10) + timestamp + suffix
    return g_object_name;
}




/**
 * 保存用户信息Ajax
 * @param name
 * @param role
 */
function ajaxSave(username, password, role, realName, img) {
    var url = $("#clicksaveRole").val();
    var data = {
        "username": username,
        "password": password,
        "role": role,
        "realName": realName,
        "img": img,
    }
    var successFunction = function (res) {
        if (res.status == 200) {
            alert("添加成功");
            window.location.href = "{{url('usermanage/index')}}";
        } else if (res.status == -1) {
            alert(res.info);
        }
    }

    var errorFunction = function (res) {
        alert("保存失败");
    }
    $.ajax({
        url: url,
        data: data,
        type: "post",
        error: errorFunction,
        success: successFunction
    });
}
/**
 * 点击保存后的判断
 * @param name
 * @param role
 */
var clicksaveRole = function () {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var role = document.getElementById("role").value;
    var realName = document.getElementById("realName").value;
    var img = document.getElementById("img").value;
    if (username == "") {
        $.msgbox("请输入用户名");
        return false;
    }
    if (password == "") {
        $.msgbox("请输入密码");
        return false;
    }
    if (role == "") {
        $.msgbox("请选择角色");
        return false;
    }
    if (realName == "") {
        $.msgbox("请输入真实姓名");
        return false;
    }
    if (img == "") {
        $.msgbox("请添加头像");
        return false;
    }

    $.msgbox({
        height: 120,
        content: {type: 'confirm', content: '确定要提交吗？'},
        onClose: function (result) {
            if (result) {
                ajaxSave(username, password, role, realName, img);
            }
        }
    });

}

$(window).load(function () {
    $("#btnsubmit").bind('click', clicksaveRole);
});

</script>
